package io.emqx;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;


public class Publish {
    public static void main(String[] args) {
        //定义连击服务器的用户名
        String username = "admin";
        //定义链接服务器的密码
        String passwd = "admin";
        //订阅主题
        String subTopic = "testtopic/#";
        String pubTopic = "testtopic/1";
        //发送消息
        String content = "Hello World";
        //服务质量
        int qos = 2;
        //服务器链接
        String broker = "tcp://www.makabaka.online:1883";
        //客户端ID
        String clientId = "emqx_test";

        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttClient client = new MqttClient(broker, clientId, persistence);

            // MQTT 连接选项  构建连接对象
            MqttConnectOptions connOpts = new MqttConnectOptions();
            // 设置连接对象的用户名和密码
            connOpts.setUserName(username);
            connOpts.setPassword(passwd.toCharArray());
            // 保留会话
            connOpts.setCleanSession(true);

            // 设置回调
            client.setCallback(new OnMessageCallback());

            // 建立连接
            System.out.println("连接到MQTT服务器: " + broker);
            client.connect(connOpts);

            System.out.println("已连接");
            System.out.println("正在发布消息: " + content);

            // 订阅
            client.subscribe(subTopic);

            // 消息发布所需参数
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            client.publish(pubTopic, message);
            System.out.println("消息已发布");

            client.disconnect();
            System.out.println("连接断开");
            client.close();
            System.exit(0);
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
}